package socket.homework3;

import socket.example4.StreamUtils;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;

/**
 * @author lhn
 * @date 2024-04-27 20:16
 * 客户端  向服务端请求音乐文件
 */

public class Homework03Client {
    public static void main(String[] args) throws IOException {
        Socket socket = new Socket(InetAddress.getByName("192.168.72.1"),9999);
        System.out.println("客户端已启动");
        System.out.println("请输入要向服务端请求的音乐文件名");
//        Scanner scanner = new Scanner(System.in);
//        String filename = scanner.next();
//        String filename = "1.mp3";
        String filename = "心做し-鹿乃.mp3";
        //将要请求的文件名字写入数据通道
        OutputStream outputStream = socket.getOutputStream();
        BufferedWriter bufferedWriter = new BufferedWriter(
                new OutputStreamWriter(outputStream)
        );
        bufferedWriter.write(filename);
        bufferedWriter.newLine();
        bufferedWriter.flush();
        System.out.println("已向服务端发送想要请求的文件");

        BufferedReader bufferedReader = new BufferedReader(
                new InputStreamReader(socket.getInputStream())
        );
        boolean isExist = Boolean.parseBoolean(bufferedReader.readLine());
        if (isExist) {
            BufferedInputStream bufferedInputStream = new BufferedInputStream(
                    socket.getInputStream()
            );
            byte[] bytes = StreamUtils.streamToByteArray(bufferedInputStream);
            //获取当前的工作目录
            String serverPath = System.setProperty("user.dir", "path/to/directory") + "\\" +filename;
            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(
                    new FileOutputStream(serverPath)
            );
            bufferedOutputStream.write(bytes);
            bufferedOutputStream.close();
            bufferedInputStream.close();
            System.out.println("已获取到文件...");
        } else {
            System.out.println("服务端上不存在该文件");
        }

        bufferedWriter.close();
        bufferedReader.close();
        socket.close();
        System.out.println("客户端关闭");
    }
}
